<template>
  <!-- AI 生成字段抽屉 -->
  <el-drawer
    v-model="dialogVisible"
    size="70%"
    direction="rtl"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="!isGenerating"
    class="ai-generate-drawer"
    :with-header="false"
  >
    <!-- 自定义头部 -->
    <div class="drawer-header">
      <div class="header-content">
        <div class="header-left">
          <h3 class="drawer-title">
            <el-icon class="title-icon"><Connection /></el-icon>
            AI 智能字段生成器
          </h3>
          <div class="connection-status" :class="connectionStatusClass">
            <el-icon class="status-icon"><Connection /></el-icon>
            <span class="status-text">{{ connectionStatusText }}</span>
          </div>
        </div>
        <div class="header-right">
          <el-button
            v-if="!isGenerating && !isParsingSql"
            type="info"
            text
            @click="dialogVisible = false"
            class="close-btn"
          >
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </div>
      
      <!-- 功能选择标签页导航 -->
      <div class="tabs-nav">
        <el-button 
          :type="activeTab === 'ai' ? 'primary' : ''"
          @click="activeTab = 'ai'"
          class="tab-button"
          :disabled="isGenerating || isParsingSql"
        >
          <el-icon><Connection /></el-icon>
          AI 智能生成
        </el-button>
        <el-button 
          :type="activeTab === 'sql' ? 'primary' : ''"
          @click="activeTab = 'sql'"
          class="tab-button"
          :disabled="isGenerating || isParsingSql"
        >
          <el-icon><DocumentAdd /></el-icon>
          SQL 导入
        </el-button>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="drawer-body">
      <!-- AI 智能生成内容 -->
      <div v-show="activeTab === 'ai'" class="tab-content-wrapper">
        <div class="tab-content ai-content">
          <!-- 输入区域 -->
          <div class="input-section">
            <el-card shadow="never" class="input-card">
              <template #header>
                <div class="card-header">
                  <span>描述您的数据表需求</span>
                  <!-- 历史记录按钮 -->
                  <el-dropdown
                    v-if="aiHistory.length > 0 && !isGenerating"
                    @command="handleHistoryCommand"
                    trigger="click"
                    class="history-dropdown"
                  >
                    <el-button type="primary" text size="small">
                      <el-icon><Clock /></el-icon>
                      历史记录
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          v-for="(item, index) in aiHistory"
                          :key="index"
                          :command="index"
                        >
                          <div class="history-item">
                            <div class="history-title">{{ item.title || '未命名' }}</div>
                            <div class="history-date">{{ formatDate(item.date) }}</div>
                          </div>
                        </el-dropdown-item>
                        <el-dropdown-item divided command="clear">
                          <el-icon><Delete /></el-icon> 清空历史记录
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </template>

              <el-input
                v-model="aiPrompt"
                type="textarea"
                :rows="4"
                placeholder="例如：创建一个用户表，包含用户基本信息、联系方式和账户状态等字段"
                :disabled="isGenerating"
                class="prompt-input"
              />

              <!-- 提示词模板选择 -->
              <div class="prompt-templates" v-if="!isGenerating">
                <div class="templates-header">
                  <span class="templates-title">
                    <el-icon><Collection /></el-icon>
                    快速模板
                  </span>
                  <el-button 
                    type="primary" 
                    text 
                    size="small"
                    @click="showCustomTemplateDialog = true"
                  >
                    <el-icon><Plus /></el-icon>
                    自定义模板
                  </el-button>
                </div>
                <div class="templates-grid">
                  <div 
                    v-for="(template, index) in promptTemplates" 
                    :key="index"
                    class="template-card"
                    @click="applyTemplate(template)"
                  >
                    <div class="template-icon">
                      <el-icon><component :is="template.icon" /></el-icon>
                    </div>
                    <div class="template-content">
                      <div class="template-title">{{ template.title }}</div>
                      <div class="template-desc">{{ template.description }}</div>
                    </div>
                  </div>
                </div>
              </div>

              <div class="input-actions">
                <el-button
                  type="primary"
                  @click="generateFields"
                  :loading="isGenerating"
                  :disabled="!aiPrompt || isGenerating || connectionStatus === 'error'"
                  size="large"
                >
                  <el-icon><Connection /></el-icon>
                  {{ isGenerating ? '生成中...' : '开始生成' }}
                </el-button>
              </div>
            </el-card>
          </div>

          <!-- 生成结果 -->
          <div v-if="aiResponse || isGenerating" class="result-section">
            <el-card shadow="never" class="result-card">
              <template #header>
                <div class="card-header">
                  <div class="header-title-section">
                    <span v-if="!isGenerating">AI 生成结果</span>
                    <div v-else class="generating-header">
                      <el-icon class="loading-icon"><Loading /></el-icon>
                      <span>AI 正在生成字段...</span>
                    </div>
                  </div>
                  <el-button
                    v-if="!isGenerating && aiResponse"
                    type="success"
                    @click="applyGeneratedFields"
                    :disabled="!aiResponse"
                    size="small"
                  >
                    <el-icon><DocumentAdd /></el-icon>
                    应用到表单
                  </el-button>
                </div>
              </template>

              <div class="response-content" ref="responseContentRef">
                <div v-if="isGenerating && !aiResponse" class="generating-placeholder">
                  <el-progress :percentage="generatingProgress" :indeterminate="true" />
                  <p class="generating-tip">正在分析您的需求，请稍候...</p>
                </div>
                <div v-else v-html="formattedAiResponse"></div>
              </div>
            </el-card>
          </div>
        </div>
      </div>

      <!-- SQL 导入内容 -->
      <div v-show="activeTab === 'sql'" class="tab-content-wrapper">
        <div class="tab-content sql-content">
          <!-- SQL 输入区域 -->
          <div class="input-section">
            <el-card shadow="never" class="input-card">
              <template #header>
                <div class="card-header">
                  <span>输入 CREATE TABLE SQL 语句</span>
                  <div class="sql-actions">
                    <el-button @click="clearSqlInput" size="small" text>
                      <el-icon><Delete /></el-icon>
                      清空
                    </el-button>
                  </div>
                </div>
              </template>

              <el-input
                v-model="sqlInput"
                type="textarea"
                :rows="10"
                placeholder="例如：
CREATE TABLE users (
  id INT PRIMARY KEY AUTO_INCREMENT,
  username VARCHAR(50) NOT NULL COMMENT '用户名',
  email VARCHAR(100) UNIQUE COMMENT '邮箱',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间'
);"
                :disabled="isParsingSql"
                class="sql-input"
              />

              <div class="input-actions">
                <el-button
                  type="primary"
                  @click="parseSqlFields"
                  :loading="isParsingSql"
                  :disabled="!sqlInput.trim()"
                  size="large"
                >
                  <el-icon><DocumentAdd /></el-icon>
                  {{ isParsingSql ? '解析中...' : '解析 SQL 字段' }}
                </el-button>
              </div>
            </el-card>
          </div>

          <!-- 解析结果 -->
          <div v-if="sqlParsedFields.length > 0" class="result-section">
            <el-card shadow="never" class="result-card">
              <template #header>
                <div class="card-header">
                  <span>解析结果 ({{ sqlParsedFields.length }} 个字段)</span>
                  <el-button
                    type="success"
                    @click="applySqlFields"
                    :disabled="sqlParsedFields.length === 0 || isParsingSql"
                    size="small"
                  >
                    <el-icon><DocumentAdd /></el-icon>
                    应用到表单
                  </el-button>
                </div>
              </template>

              <div class="parsed-fields-preview">
                <el-table :data="sqlParsedFields" border size="small" style="width: 100%" max-height="400">
                  <el-table-column prop="name" label="字段名" width="140" />
                  <el-table-column prop="columnName" label="数据库字段" width="140" />
                  <el-table-column prop="type" label="数据类型" width="100">
                    <template #default="scope">
                      <el-tag size="small" type="info">
                        {{ getDataTypeLabel(scope.row.dataType) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="required" label="必填" width="80" align="center">
                    <template #default="scope">
                      <el-tag :type="scope.row.required === 1 ? 'danger' : 'success'" size="small">
                        {{ scope.row.required === 1 ? '是' : '否' }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="comment" label="描述" min-width="200" />
                </el-table>
              </div>
            </el-card>
          </div>

          <!-- 错误信息 -->
          <div v-if="sqlParseError" class="error-section">
            <el-card shadow="never" class="error-card">
              <el-alert
                :title="sqlParseError"
                type="error"
                :closable="false"
                show-icon
              />
            </el-card>
          </div>
        </div>
      </div>
    </div>


  </el-drawer>

  <!-- 保存到历史记录对话框 -->
  <el-dialog
    title="保存到历史记录"
    v-model="showSaveHistoryDialog"
    width="30%"
  >
    <el-form>
      <el-form-item label="标题">
        <el-input v-model="historyTitle" placeholder="请输入标题，便于后续查找" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showSaveHistoryDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmSaveHistory">保存</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 自定义模板对话框 -->
  <el-dialog
    title="自定义提示词模板"
    v-model="showCustomTemplateDialog"
    width="50%"
  >
    <el-form :model="customTemplate" label-width="80px">
      <el-form-item label="模板名称">
        <el-input v-model="customTemplate.title" placeholder="请输入模板名称" />
      </el-form-item>
      <el-form-item label="模板描述">
        <el-input v-model="customTemplate.description" placeholder="请输入模板描述" />
      </el-form-item>
      <el-form-item label="提示词内容">
        <el-input 
          v-model="customTemplate.prompt" 
          type="textarea" 
          :rows="6"
          placeholder="请输入提示词内容"
        />
      </el-form-item>
      <el-form-item label="图标">
        <el-select v-model="customTemplate.icon" placeholder="选择图标">
          <el-option label="用户" value="User" />
          <el-option label="商品" value="Goods" />
          <el-option label="订单" value="Document" />
          <el-option label="设置" value="Setting" />
          <el-option label="数据" value="DataBoard" />
          <el-option label="文件" value="Files" />
          <el-option label="消息" value="Message" />
          <el-option label="钱包" value="Wallet" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showCustomTemplateDialog = false">取消</el-button>
        <el-button type="primary" @click="saveCustomTemplate">保存模板</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onUnmounted, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Loading, Connection, Clock, ArrowDown, Delete, DocumentAdd, Close, Collection, Plus, User, Goods, Document, Setting, DataBoard, Files, Message, Wallet } from '@element-plus/icons-vue'
import config from '@/config/index.js'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  modelName: {
    type: String,
    default: ''
  },
  tableName: {
    type: String,
    default: ''
  },
  description: {
    type: String,
    default: ''
  },
  existingFields: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:visible', 'apply-fields'])

// 对话框可见性
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

// 标签页状态
const activeTab = ref('ai')

// AI 生成相关
const aiPrompt = ref('')
const aiResponse = ref('')
const aiThinking = ref('') // 存储思考过程
const aiResult = ref('') // 存储最终结果
const isGenerating = ref(false)
const generatingProgress = ref(0)
const websocket = ref(null)
const parsedFields = ref([])
const connectionStatus = ref('pending') // pending, connected, error
const canSaveToHistory = ref(true) // 控制是否可以保存到历史
const reconnectTimer = ref(null) // 重连定时器
const reconnectAttempts = ref(0) // 重连尝试次数
const MAX_RECONNECT_ATTEMPTS = 5 // 最大重连次数
const responseContentRef = ref(null) // 响应内容区域的引用

// SQL 导入相关
const sqlInput = ref('')
const sqlParsedFields = ref([])
const isParsingSql = ref(false)
const sqlParseError = ref('')

// 历史记录相关
const aiHistory = ref([])
const showSaveHistoryDialog = ref(false)
const historyTitle = ref('')
const HISTORY_STORAGE_KEY = 'ai_fields_generation_history'

// 提示词模板相关
const showCustomTemplateDialog = ref(false)
const customTemplate = ref({
  title: '',
  description: '',
  prompt: '',
  icon: 'User'
})
const TEMPLATES_STORAGE_KEY = 'ai_prompt_templates'

// 预设提示词模板
const defaultTemplates = [
  {
    title: '用户管理表',
    description: '包含用户基本信息、权限等',
    icon: 'User',
    prompt: '创建一个用户管理表，包含用户基本信息（用户名、邮箱、手机号）、账户状态、权限角色、注册时间、最后登录时间等字段'
  },
  {
    title: '商品信息表',
    description: '电商商品的基础信息',
    icon: 'Goods',
    prompt: '创建一个商品信息表，包含商品名称、商品编码、价格、库存、分类、品牌、商品描述、商品状态、创建时间等字段'
  },
  {
    title: '订单管理表',
    description: '订单相关的核心字段',
    icon: 'Document',
    prompt: '创建一个订单管理表，包含订单号、用户ID、商品信息、订单金额、支付状态、配送地址、下单时间、支付时间等字段'
  },
  {
    title: '系统配置表',
    description: '系统参数配置管理',
    icon: 'Setting',
    prompt: '创建一个系统配置表，包含配置键名、配置值、配置描述、配置分组、是否启用、创建时间、更新时间等字段'
  },
  {
    title: '日志记录表',
    description: '系统操作日志记录',
    icon: 'DataBoard',
    prompt: '创建一个日志记录表，包含操作用户、操作模块、操作类型、操作内容、IP地址、浏览器信息、操作时间等字段'
  },
  {
    title: '文件管理表',
    description: '文件上传和管理',
    icon: 'Files',
    prompt: '创建一个文件管理表，包含文件名、原始文件名、文件路径、文件大小、文件类型、上传用户、上传时间、文件状态等字段'
  }
]

// 合并默认模板和自定义模板
const promptTemplates = computed(() => {
  const customTemplates = JSON.parse(localStorage.getItem(TEMPLATES_STORAGE_KEY) || '[]')
  return [...defaultTemplates, ...customTemplates]
})

// 连接状态文本
const connectionStatusText = computed(() => {
  switch (connectionStatus.value) {
    case 'pending':
      return '正在连接 AI 服务...'
    case 'connected':
      return 'AI 服务已连接'
    case 'error':
      return 'AI 服务连接失败'
    default:
      return '未知状态'
  }
})

// 连接状态样式类
const connectionStatusClass = computed(() => {
  return {
    'status-pending': connectionStatus.value === 'pending',
    'status-connected': connectionStatus.value === 'connected',
    'status-error': connectionStatus.value === 'error'
  }
})

// 格式化 AI 响应，将换行符转换为 <br>
const formattedAiResponse = computed(() => {
  // 如果有最终结果，优先显示结果，否则显示思考过程
  const content = aiResult.value || aiThinking.value || aiResponse.value
  return content.replace(/\n/g, '<br>')
})

// 格式化日期
const formatDate = (timestamp) => {
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 加载历史记录
const loadHistory = () => {
  try {
    const historyData = localStorage.getItem(HISTORY_STORAGE_KEY)
    if (historyData) {
      aiHistory.value = JSON.parse(historyData)
    }
  } catch (error) {
    console.error('加载历史记录失败:', error)
    aiHistory.value = []
  }
}

// 保存历史记录
const saveHistory = () => {
  try {
    localStorage.setItem(HISTORY_STORAGE_KEY, JSON.stringify(aiHistory.value))
  } catch (error) {
    console.error('保存历史记录失败:', error)
    ElMessage.error('保存历史记录失败')
  }
}

// 确认保存到历史记录
const confirmSaveHistory = () => {
  const historyItem = {
    title: historyTitle.value || '未命名',
    prompt: aiPrompt.value,
    thinking: aiThinking.value,
    result: aiResult.value,
    response: aiResponse.value,
    fields: parsedFields.value.length > 0 ? parsedFields.value : [],
    date: Date.now()
  }

  // 检查是否已存在相同内容的历史记录
  const existingIndex = aiHistory.value.findIndex(item =>
    item.prompt === historyItem.prompt &&
    (item.result === historyItem.result || item.response === historyItem.response)
  )

  if (existingIndex !== -1) {
    // 如果已存在，更新该记录
    aiHistory.value[existingIndex] = historyItem
    ElMessage.success('已更新历史记录')
  } else {
    // 如果不存在，添加新记录
    aiHistory.value.unshift(historyItem) // 添加到历史记录开头

    // 限制历史记录数量，最多保存20条
    if (aiHistory.value.length > 20) {
      aiHistory.value = aiHistory.value.slice(0, 20)
    }

    ElMessage.success('已保存到历史记录')
  }

  saveHistory()
  showSaveHistoryDialog.value = false
  canSaveToHistory.value = false // 保存后禁用保存按钮
}

// 处理历史记录命令
const handleHistoryCommand = (command) => {
  if (command === 'clear') {
    ElMessageBox.confirm('确定要清空所有历史记录吗？此操作不可恢复。', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      aiHistory.value = []
      saveHistory()
      ElMessage.success('历史记录已清空')
    }).catch(() => {})
    return
  }

  // 加载选中的历史记录
  const historyItem = aiHistory.value[command]
  if (historyItem) {
    aiPrompt.value = historyItem.prompt || ''
    aiThinking.value = historyItem.thinking || ''
    aiResult.value = historyItem.result || ''
    aiResponse.value = historyItem.result || historyItem.thinking || historyItem.response || ''

    if (historyItem.fields && historyItem.fields.length > 0) {
      parsedFields.value = historyItem.fields
    }

    canSaveToHistory.value = false // 从历史记录加载的内容不能再次保存
    ElMessage.success('已加载历史记录')

    // 加载历史记录后滚动到底部
    scrollResponseToBottom()
  }
}

// 监听响应内容变化，自动滚动到底部
watch([aiResponse, aiThinking, aiResult], () => {
  scrollResponseToBottom()
}, { immediate: false })

// 滚动响应内容到底部
const scrollResponseToBottom = () => {
  nextTick(() => {
    if (responseContentRef.value) {
      responseContentRef.value.scrollTop = responseContentRef.value.scrollHeight
    }
  })
}

// 连接 AI 服务
const connectToAiService = () => {
  // 如果已经有连接，先关闭
  if (websocket.value && websocket.value.readyState !== WebSocket.CLOSED) {
    websocket.value.close()
  }

  // 重置重连计数
  reconnectAttempts.value = 0

  // 更新连接状态
  connectionStatus.value = 'pending'

  // 创建 WebSocket 连接
  try {
    const wsUrl = `${config.API_URL}/websocket`
    websocket.value = new WebSocket(wsUrl)

    websocket.value.onopen = () => {
      console.log('WebSocket 连接已建立')
      connectionStatus.value = 'connected'
      // 清除重连定时器
      if (reconnectTimer.value) {
        clearTimeout(reconnectTimer.value)
        reconnectTimer.value = null
      }
    }

    websocket.value.onclose = (event) => {
      console.log('WebSocket 连接已关闭', event)

      if (isGenerating.value) {
        isGenerating.value = false
        ElMessage.info('AI 服务连接已关闭')

        // 连接关闭时，最后一次尝试解析字段
        tryParseFieldsFromContent(aiResult.value || aiThinking.value || aiResponse.value)
      }

      // 如果不是主动关闭，尝试重连
      if (dialogVisible.value && connectionStatus.value !== 'error' && reconnectAttempts.value < MAX_RECONNECT_ATTEMPTS) {
        scheduleReconnect()
      } else if (reconnectAttempts.value >= MAX_RECONNECT_ATTEMPTS) {
        connectionStatus.value = 'error'
        ElMessage.error('连接 AI 服务失败，请稍后重试')
      }
    }

    websocket.value.onerror = (error) => {
      console.error('WebSocket 错误:', error)
      connectionStatus.value = 'error'

      if (isGenerating.value) {
        isGenerating.value = false
        ElMessage.error('连接 AI 服务出错')
      }
    }

    websocket.value.onmessage = (event) => {
      try {
        // 尝试解析 JSON
        const data = JSON.parse(event.data)

        if (data.messageType === 'reasoning') {
          // 处理思考过程
          aiThinking.value += data.content || ''
          aiResponse.value = aiThinking.value // 更新显示的响应
          scrollResponseToBottom() // 滚动到底部
        } else if (data.messageType === 'answer' || data.messageType === 'content') {
          // 处理最终结果
          if (data.content || data.message) {
            aiResult.value += data.content || data.message || ''
            aiResponse.value = aiResult.value // 更新显示的响应
            scrollResponseToBottom() // 滚动到底部

            // 尝试解析字段
            tryParseFieldsFromContent(aiResult.value)
          }
        } else if (data.messageType === 'over') {
          // 生成结束
          isGenerating.value = false
          ElMessage.success('AI 字段生成完成')

          // 最后一次尝试解析字段
          tryParseFieldsFromContent(aiResult.value || aiThinking.value)
        }
      } catch (error) {
        // 如果不是 JSON 格式，直接作为文本处理
        if (isGenerating.value) {
          aiResponse.value += event.data
          scrollResponseToBottom() // 滚动到底部
        }
      }
    }
  } catch (error) {
    console.error('创建 WebSocket 连接出错:', error)
    connectionStatus.value = 'error'
    ElMessage.error('连接 AI 服务失败')
  }
}

// 安排重连
const scheduleReconnect = () => {
  reconnectAttempts.value++
  const delay = Math.min(1000 * Math.pow(2, reconnectAttempts.value - 1), 10000) // 指数退避，最大10秒

  console.log(`第 ${reconnectAttempts.value} 次重连尝试，${delay}ms 后重连`)

  reconnectTimer.value = setTimeout(() => {
    connectToAiService()
  }, delay)
}

// 生成字段
const generateFields = () => {
  if (!aiPrompt.value) {
    ElMessage.warning('请输入数据表需求描述')
    return
  }

  if (connectionStatus.value === 'error') {
    ElMessage.error('AI 服务连接失败，请稍后重试')
    return
  }

  if (connectionStatus.value !== 'connected') {
    ElMessage.warning('正在连接 AI 服务，请稍候再试')
    return
  }

  isGenerating.value = true
  aiThinking.value = '' // 清空思考过程
  aiResult.value = '' // 清空最终结果
  aiResponse.value = '' // 清空显示的响应
  parsedFields.value = []
  generatingProgress.value = 0
  canSaveToHistory.value = true // 新生成的内容可以保存

  // 构建提示词，包含更多上下文信息
  const modelName = props.modelName || '未命名模型'
  const tableName = props.tableName || '未命名表'

  // 发送提示词
  websocket.value.send(JSON.stringify({
    type: 'prompt',
    message: `请帮我设计一个数据表，需求如下：${aiPrompt.value}

模型名称：${modelName}
表名：${tableName}

请以JSON格式返回字段定义，严格按照以下格式和规范：

## 字段结构说明：
{
  "name": "中文显示名称",           // 用于前端显示的中文字段名
  "javaName": "javaVariableName",  // Java变量名，驼峰命名法
  "columnName": "column_name",     // 数据库字段名，下划线命名法
  "dataType": 数字,                // 数据类型编号（见下方映射表）
  "required": 1/-1,               // 是否必填：1=必填，-1=非必填
  "unique": 1/-1,                 // 是否唯一：1=唯一，-1=非唯一
  "persistent": 1,                // 是否持久化：固定为1
  "defaultValue": "默认值",        // 字段默认值，字符串格式
  "description": "字段描述"        // 详细的字段说明
}

## 数据类型映射表（dataType字段使用对应数字）：
1  - String（字符串）
2  - Integer（整数）
3  - Long（长整数）
4  - Double（双精度浮点数）
5  - Float（单精度浮点数）
6  - Boolean（布尔值）
7  - Date（日期）
8  - LocalDateTime（日期时间）
9  - LocalDate（日期）
10 - LocalTime（时间）
11 - BigDecimal（高精度小数）
12 - Byte（字节）
13 - Short（短整数）
14 - Character（字符）
15 - byte[]（字节数组）
16 - List（列表）
17 - JSON（JSON对象）

## 示例格式：
[
  {
    "name": "用户ID",
    "javaName": "userId",
    "columnName": "user_id",
    "dataType": 3,
    "required": 1,
    "unique": 1,
    "persistent": 1,
    "defaultValue": "",
    "description": "用户唯一标识符，主键"
  },
  {
    "name": "用户名",
    "javaName": "username",
    "columnName": "username",
    "dataType": 1,
    "required": 1,
    "unique": 1,
    "persistent": 1,
    "defaultValue": "",
    "description": "用户登录名，唯一不重复"
  }
]

## 设计要求：
1. 数据库字段名使用下划线命名法（snake_case）
2. Java变量名使用驼峰命名法（camelCase）
3. 中文显示名要简洁明了，便于用户理解
4. 根据业务需求合理选择数据类型
5. 主键字段建议使用Long类型（dataType: 3）
6. 时间字段优先使用LocalDateTime（dataType: 8）
7. 金额字段使用BigDecimal（dataType: 11）
8. 状态字段可使用Integer（dataType: 2）
9. 描述性文本使用String（dataType: 1）
10. 必填字段设置required: 1，非必填设置required: -1
11. 需要唯一性约束的字段设置unique: 1，否则设置unique: -1

请根据以上规范生成完整的字段定义JSON数组。`
  }))
}

// 应用生成的字段
const applyGeneratedFields = () => {
  if (!aiResponse.value) {
    ElMessage.warning('没有生成的字段可应用')
    return
  }

  try {
    // 首先检查是否已经成功解析了字段
    if (parsedFields.value.length > 0) {
      emit('apply-fields', parsedFields.value)
      dialogVisible.value = false
      ElMessage.success('已应用 AI 生成的字段')
      return
    }

    // 如果没有预解析的字段，尝试从响应中提取 JSON 格式的字段定义
    const content = aiResult.value || aiThinking.value
    tryParseFieldsFromContent(content)

    if (parsedFields.value.length > 0) {
      emit('apply-fields', parsedFields.value)
      dialogVisible.value = false
      ElMessage.success('已应用 AI 生成的字段')
    } else {
      ElMessage.warning('无法解析字段定义，请检查生成结果或手动添加字段')
    }
  } catch (error) {
    console.error('应用生成字段出错:', error)
    ElMessage.error('应用生成字段失败，请检查生成结果格式或手动添加字段')
  }
}

// 尝试从内容中提取 JSON 字段定义
const tryParseFieldsFromContent = (content) => {
  if (!content) return

  try {
    // 首先尝试从内容中提取 JSON 数组
    const jsonMatches = content.match(/\[\s*\{[^]*?\}\s*\]/gs)

    if (jsonMatches && jsonMatches.length > 0) {
      // 取最后一个匹配结果，通常是最完整的
      const jsonStr = jsonMatches[jsonMatches.length - 1]

      try {
        const fieldsData = JSON.parse(jsonStr)

        if (Array.isArray(fieldsData) && fieldsData.length > 0) {
          // 验证字段格式
          const validFields = fieldsData.filter(field =>
            field && typeof field === 'object' && 
            field.name && typeof field.name === 'string' &&
            field.javaName && typeof field.javaName === 'string' &&
            field.columnName && typeof field.columnName === 'string'
          )

          if (validFields.length > 0) {
            parsedFields.value = validFields.map(field => ({
              id: null,
              name: field.name,
              javaName: field.javaName,
              columnName: field.columnName,
              dataType: field.dataType || 1,
              required: field.required || -1,
              unique: field.unique || -1,
              persistent: field.persistent || 1,
              detailState: -1,
              relatedModule: null,
              foreignState: -1,
              state: 1,
              defaultValue: field.defaultValue || '',
              comment: field.description || '',
              validation: ''
            }))

            // 成功解析字段
          }
        }
      } catch (jsonError) {
        // JSON 解析失败
      }
    } else {
      // 如果没有找到 JSON 数组，尝试解析文本格式
      // 未找到 JSON 格式，尝试解析文本格式

      // 尝试查找字段定义的文本模式
      const fieldPattern = /(\w+)\s*\((\w+)\)(?:\s*\((\w+)\))?\s*:\s*(.+?)(?=\n\w+\s*\(|\n\s*\n|$)/gs
      const matches = [...content.matchAll(fieldPattern)]

      if (matches.length > 0) {
        const textFields = matches.map(match => {
          const fieldName = match[1]
          const javaName = fieldName.replace(/_([a-z])/g, (match, letter) => letter.toUpperCase())
          
          return {
            id: null,
            name: fieldName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()),
            javaName: javaName,
            columnName: fieldName,
            dataType: 1, // 默认为String
            required: match[3] === 'required' ? 1 : -1,
            unique: -1,
            persistent: 1,
            detailState: -1,
            relatedModule: null,
            foreignState: -1,
            state: 1,
            defaultValue: '',
            comment: match[4] || '',
            validation: ''
          }
        })

        if (textFields.length > 0) {
          parsedFields.value = textFields
          // 从文本格式解析字段
        }
      }
    }
  } catch (error) {
    console.log('尝试解析字段失败:', error)
  }
}

// SQL 解析相关函数
const parseSqlFields = () => {
  if (!sqlInput.value.trim()) {
    ElMessage.warning('请输入 SQL 语句')
    return
  }

  isParsingSql.value = true
  sqlParseError.value = ''
  sqlParsedFields.value = []

  try {
    const fields = parseSqlCreateTable(sqlInput.value)
    if (fields.length > 0) {
      // 过滤已存在的字段
      const existingFieldNames = props.existingFields.map(f => f.columnName?.toLowerCase() || f.name?.toLowerCase()).filter(Boolean)
      const newFields = fields.filter(field =>
        !existingFieldNames.includes(field.columnName.toLowerCase())
      )

      if (newFields.length < fields.length) {
        const filteredCount = fields.length - newFields.length
        ElMessage.info(`已过滤 ${filteredCount} 个重复字段`)
      }

      sqlParsedFields.value = newFields
      ElMessage.success(`成功解析 ${newFields.length} 个字段`)
    } else {
      sqlParseError.value = '未能解析出任何字段，请检查 SQL 语句格式'
    }
  } catch (error) {
    console.error('SQL 解析错误:', error)
    sqlParseError.value = error.message || '解析 SQL 语句时发生错误'
  } finally {
    isParsingSql.value = false
  }
}

// 解析 CREATE TABLE SQL 语句
const parseSqlCreateTable = (sql) => {
  const fields = []

  try {
    // 清理 SQL 语句，移除多余的空白字符和注释
    let cleanSql = sql.replace(/--.*$/gm, '').replace(/\/\*[\s\S]*?\*\//g, '').trim()

    // 提取表定义部分
    const tableMatch = cleanSql.match(/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?`?(\w+)`?\s*\(([\s\S]*)\)/i)
    if (!tableMatch) {
      throw new Error('无法识别 CREATE TABLE 语句格式')
    }

    const tableDefinition = tableMatch[2]

    // 分割字段定义，处理括号内的内容
    const fieldDefinitions = splitFieldDefinitions(tableDefinition)

    fieldDefinitions.forEach((fieldDef, index) => {
      const field = parseFieldDefinition(fieldDef.trim())
      if (field) {
        fields.push(field)
      }
    })

  } catch (error) {
    throw new Error(`SQL 解析失败: ${error.message}`)
  }

  return fields
}

// 分割字段定义
const splitFieldDefinitions = (definition) => {
  const fields = []
  let current = ''
  let parenthesesCount = 0
  let inQuotes = false
  let quoteChar = ''

  for (let i = 0; i < definition.length; i++) {
    const char = definition[i]

    if (!inQuotes && (char === '"' || char === "'" || char === '`')) {
      inQuotes = true
      quoteChar = char
    } else if (inQuotes && char === quoteChar) {
      inQuotes = false
      quoteChar = ''
    } else if (!inQuotes) {
      if (char === '(') {
        parenthesesCount++
      } else if (char === ')') {
        parenthesesCount--
      } else if (char === ',' && parenthesesCount === 0) {
        if (current.trim()) {
          fields.push(current.trim())
        }
        current = ''
        continue
      }
    }

    current += char
  }

  if (current.trim()) {
    fields.push(current.trim())
  }

  return fields.filter(field =>
    !field.match(/^\s*(PRIMARY\s+KEY|FOREIGN\s+KEY|KEY|INDEX|UNIQUE\s+KEY|CONSTRAINT)/i)
  )
}

// 解析单个字段定义
const parseFieldDefinition = (fieldDef) => {
  try {
    // 匹配字段定义的各个部分
    const fieldMatch = fieldDef.match(/^`?(\w+)`?\s+(\w+)(?:\(([^)]+)\))?\s*(.*)/i)
    if (!fieldMatch) {
      return null
    }

    const [, columnName, sqlType, typeParams, constraints] = fieldMatch

    // 转换数据类型
    const dataType = mapSqlTypeToDataType(sqlType, typeParams)

    // 检查是否必填
    const isRequired = /NOT\s+NULL/i.test(constraints) ? 1 : -1

    // 检查是否唯一
    const isUnique = /UNIQUE/i.test(constraints) ? 1 : 0

    // 提取默认值
    let defaultValue = ''
    const defaultMatch = constraints.match(/DEFAULT\s+([^,\s]+)/i)
    if (defaultMatch) {
      defaultValue = defaultMatch[1].replace(/['"]/g, '')
    }

    // 提取注释
    let comment = ''
    const commentMatch = constraints.match(/COMMENT\s+['"](.*?)['"]/i)
    if (commentMatch) {
      comment = commentMatch[1]
    }

    // 生成显示名称（将下划线转换为空格并首字母大写）
    const displayName = columnName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())

    // 生成 Java 变量名（驼峰命名）
    const javaName = columnName.replace(/_([a-z])/g, (match, letter) => letter.toUpperCase())

    return {
      id: null,
      name: displayName,
      javaName: javaName,
      columnName: columnName,
      dataType: dataType,
      required: isRequired,
      unique: isUnique,
      persistent: 1,
      detailState: -1,
      relatedModule: null,
      foreignState: -1,
      state: 1,
      defaultValue: defaultValue,
      comment: comment,
      validation: ''
    }
  } catch (error) {
    console.error('解析字段定义失败:', fieldDef, error)
    return null
  }
}

// 将 SQL 数据类型映射到系统数据类型
const mapSqlTypeToDataType = (sqlType, typeParams) => {
  const type = sqlType.toUpperCase()

  switch (type) {
    case 'VARCHAR':
    case 'CHAR':
    case 'TEXT':
    case 'LONGTEXT':
    case 'MEDIUMTEXT':
    case 'TINYTEXT':
      return 1 // String
    case 'TINYINT':
      // 如果长度为1，通常表示布尔值
      if (typeParams === '1') {
        return 6 // Boolean
      }
      return 12 // Byte
    case 'SMALLINT':
      return 13 // Short
    case 'INT':
    case 'INTEGER':
      return 2 // Integer
    case 'BIGINT':
      return 3 // Long
    case 'FLOAT':
      return 5 // Float
    case 'DOUBLE':
      return 4 // Double
    case 'DECIMAL':
    case 'NUMERIC':
      return 11 // BigDecimal
    case 'BOOLEAN':
    case 'BOOL':
      return 6 // Boolean
    case 'DATE':
      return 9 // LocalDate
    case 'TIME':
      return 10 // LocalTime
    case 'DATETIME':
    case 'TIMESTAMP':
      return 8 // LocalDateTime
    case 'JSON':
      return 17 // JSON
    case 'BLOB':
    case 'LONGBLOB':
    case 'MEDIUMBLOB':
    case 'TINYBLOB':
    case 'BINARY':
    case 'VARBINARY':
      return 15 // byte[]
    default:
      return 1 // 默认为String
  }
}

// 获取数据类型标签
const getDataTypeLabel = (dataType) => {
  const typeMap = {
    1: 'String',
    2: 'Integer',
    3: 'Long',
    4: 'Double',
    5: 'Float',
    6: 'Boolean',
    7: 'Date',
    8: 'LocalDateTime',
    9: 'LocalDate',
    10: 'LocalTime',
    11: 'BigDecimal',
    12: 'Byte',
    13: 'Short',
    14: 'Character',
    15: 'byte[]',
    16: 'List',
    17: 'JSON'
  }
  return typeMap[dataType] || '未知'
}

// 清空 SQL 输入
const clearSqlInput = () => {
  sqlInput.value = ''
  sqlParsedFields.value = []
  sqlParseError.value = ''
}

// 应用 SQL 解析的字段
const applySqlFields = () => {
  if (sqlParsedFields.value.length === 0) {
    ElMessage.warning('没有解析到字段')
    return
  }

  emit('apply-fields', sqlParsedFields.value)
  dialogVisible.value = false
  ElMessage.success(`已应用 ${sqlParsedFields.value.length} 个字段`)
}

// 监听对话框显示状态
watch(dialogVisible, (newVal) => {
  if (newVal) {
    // 对话框打开时，重置状态
    activeTab.value = 'ai'

    // 构建更丰富的提示词
    let promptText = ''

    if (props.modelName) {
      promptText += `创建一个"${props.modelName}"数据表`
    } else {
      promptText += '创建一个数据表'
    }

    if (props.description) {
      promptText += `，描述如下：${props.description}`
    }

    if (props.tableName) {
      promptText += `\n表名：${props.tableName}`
    }

    // 重置 AI 相关状态
    aiPrompt.value = promptText
    aiResponse.value = ''
    aiThinking.value = ''
    aiResult.value = ''
    parsedFields.value = []
    canSaveToHistory.value = true // 重置保存状态

    // 重置 SQL 相关状态
    sqlInput.value = ''
    sqlParsedFields.value = []
    sqlParseError.value = ''
    isParsingSql.value = false

    // 连接 AI 服务
    connectToAiService()
  } else {
    // 对话框关闭时，如果不在生成中，关闭 WebSocket 连接
    if (!isGenerating.value && websocket.value) {
      websocket.value.close()
    }

    // 清除重连定时器
    if (reconnectTimer.value) {
      clearTimeout(reconnectTimer.value)
      reconnectTimer.value = null
    }
  }
})

// 应用提示词模板
const applyTemplate = (template) => {
  aiPrompt.value = template.prompt
  ElMessage.success(`已应用模板：${template.title}`)
}

// 保存自定义模板
const saveCustomTemplate = () => {
  if (!customTemplate.value.title || !customTemplate.value.prompt) {
    ElMessage.warning('请填写模板名称和提示词内容')
    return
  }

  try {
    const existingTemplates = JSON.parse(localStorage.getItem(TEMPLATES_STORAGE_KEY) || '[]')
    
    // 检查是否已存在相同名称的模板
    const existingIndex = existingTemplates.findIndex(t => t.title === customTemplate.value.title)
    
    if (existingIndex !== -1) {
      // 更新现有模板
      existingTemplates[existingIndex] = { ...customTemplate.value }
      ElMessage.success('模板已更新')
    } else {
      // 添加新模板
      existingTemplates.push({ ...customTemplate.value })
      ElMessage.success('模板已保存')
    }

    localStorage.setItem(TEMPLATES_STORAGE_KEY, JSON.stringify(existingTemplates))
    
    // 重置表单
    customTemplate.value = {
      title: '',
      description: '',
      prompt: '',
      icon: 'User'
    }
    
    showCustomTemplateDialog.value = false
  } catch (error) {
    console.error('保存模板失败:', error)
    ElMessage.error('保存模板失败')
  }
}

// 组件挂载时加载历史记录
onMounted(() => {
  // 加载历史记录
  loadHistory()
})

// 监听组件销毁
onUnmounted(() => {
  console.log('AI字段生成组件卸载，关闭 WebSocket 连接')

  // 关闭 WebSocket 连接
  if (websocket.value) {
    try {
      websocket.value.close()
      websocket.value = null
    } catch (error) {
      console.error('关闭 WebSocket 连接出错:', error)
    }
  }

  // 清除重连定时器
  if (reconnectTimer.value) {
    clearTimeout(reconnectTimer.value)
    reconnectTimer.value = null
  }
})
</script>

<style scoped>
/* 抽屉头部样式 */
.drawer-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px 16px;
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.drawer-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 10px;
  letter-spacing: 0.5px;
}

.title-icon {
  font-size: 22px;
  filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.2));
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  opacity: 0.9;
  padding: 4px 8px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
}

.status-icon {
  font-size: 14px;
}

.status-text {
  font-weight: 400;
}

.status-pending .status-icon {
  color: #ffd700;
  animation: pulse 2s infinite;
}

.status-connected .status-icon {
  color: #52c41a;
}

.status-error .status-icon {
  color: #ff4d4f;
}

.header-right {
  display: flex;
  align-items: center;
}

.close-btn {
  color: white !important;
  font-size: 20px;
  padding: 8px;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background-color: rgba(255, 255, 255, 0.15) !important;
  transform: scale(1.1);
}

/* 标签页导航样式 */
.tabs-nav {
  display: flex;
  gap: 2px;
  padding: 0 24px 16px;
  justify-content: center;
}

.tab-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  border-radius: 20px;
  font-weight: 500;
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.3);
  background: rgba(255, 255, 255, 0.1);
  color: white;
  backdrop-filter: blur(10px);
  min-width: 140px;
  justify-content: center;
}

.tab-button:hover:not(.el-button--primary):not(:disabled) {
  border-color: rgba(255, 255, 255, 0.5);
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-1px);
}

.tab-button.el-button--primary {
  background: rgba(255, 255, 255, 0.9);
  border-color: rgba(255, 255, 255, 0.9);
  color: #667eea;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.tab-button.el-button--primary:hover {
  background: white;
  border-color: white;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.tab-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 抽屉主体样式 */
.drawer-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: linear-gradient(180deg, #f8f9fa 0%, #ffffff 100%);
}



/* 响应内容样式 */
.response-content {
  white-space: pre-wrap;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  line-height: 1.7;
  color: #2c3e50;
  background: linear-gradient(135deg, #f8f9ff 0%, #ffffff 100%);
  border-radius: 12px;
  padding: 20px;
  overflow-y: auto;
  max-height: 350px;
  border: 2px solid rgba(102, 126, 234, 0.1);
  scroll-behavior: smooth;
  position: relative;
}

.response-content::-webkit-scrollbar {
  width: 6px;
}

.response-content::-webkit-scrollbar-track {
  background: rgba(102, 126, 234, 0.1);
  border-radius: 3px;
}

.response-content::-webkit-scrollbar-thumb {
  background: rgba(102, 126, 234, 0.3);
  border-radius: 3px;
}

.response-content::-webkit-scrollbar-thumb:hover {
  background: rgba(102, 126, 234, 0.5);
}

/* 表格样式优化 */
.parsed-fields-preview :deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

.parsed-fields-preview :deep(.el-table th) {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #495057;
}

.parsed-fields-preview :deep(.el-table td) {
  padding: 12px 8px;
}

.parsed-fields-preview :deep(.el-table--border) {
  border: 1px solid #e9ecef;
}

/* 历史记录样式 */
.history-dropdown {
  margin-left: auto;
}

.history-item {
  display: flex;
  flex-direction: column;
  max-width: 220px;
  padding: 8px 0;
  transition: all 0.2s ease;
}

.history-title {
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #303133;
  font-size: 13px;
}

.history-date {
  font-size: 11px;
  color: #909399;
  margin-top: 4px;
  font-weight: 400;
}

/* 动画效果 */
@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideInFromLeft {
  from {
    opacity: 0;
    transform: translateX(-30px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes slideInFromRight {
  from {
    opacity: 0;
    transform: translateX(30px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes shimmer {
  0% {
    background-position: -200px 0;
  }
  100% {
    background-position: calc(200px + 100%) 0;
  }
}

.ai-connection-status {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  margin-bottom: 16px;
  border-radius: 4px;
  font-size: 14px;
}

.ai-connection-status .el-icon {
  margin-right: 8px;
}

.status-pending {
  background-color: #e6f7ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.status-connected {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.status-error {
  background-color: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.history-container {
  margin: 16px 0;
  display: flex;
  justify-content: flex-start;
}

.history-item {
  display: flex;
  flex-direction: column;
  max-width: 200px;
}

.history-title {
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.history-date {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* AI 生成抽屉整体样式 */
:deep(.ai-generate-drawer .el-drawer) {
  display: flex;
  flex-direction: column;
  background: linear-gradient(180deg, #ffffff 0%, #f8f9fa 100%);
  box-shadow: -4px 0 20px rgba(0, 0, 0, 0.1);
}

:deep(.ai-generate-drawer .el-drawer__body) {
  overflow: hidden;
  flex: 1;
  padding: 0;
  display: flex;
  flex-direction: column;
}

:deep(.ai-generate-drawer .el-drawer__header) {
  display: none;
}



/* 内容区域样式 */
.tab-content-wrapper {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  scroll-behavior: smooth;
}

.tab-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
  max-width: 100%;
}

.ai-content {
  animation: slideInFromLeft 0.4s ease-out;
}

.sql-content {
  animation: slideInFromRight 0.4s ease-out;
}

/* 卡片样式 */
.input-card,
.result-card,
.status-card,
.error-card {
  border-radius: 16px;
  border: 1px solid rgba(102, 126, 234, 0.1);
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.08);
  transition: all 0.3s ease;
  background: white;
  overflow: hidden;
}

.input-card:hover,
.result-card:hover {
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.15);
  transform: translateY(-2px);
  border-color: rgba(102, 126, 234, 0.2);
}

.status-card {
  background: linear-gradient(135deg, #f8f9ff 0%, #ffffff 100%);
  border-color: rgba(102, 126, 234, 0.2);
}

.error-card {
  background: linear-gradient(135deg, #fff5f5 0%, #ffffff 100%);
  border-color: rgba(255, 77, 79, 0.2);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #303133;
  padding: 20px 24px 16px;
  background: linear-gradient(135deg, #f8f9ff 0%, #ffffff 100%);
  border-bottom: 1px solid rgba(102, 126, 234, 0.1);
}

.header-title-section {
  display: flex;
  align-items: center;
}

.generating-header {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #667eea;
  font-weight: 600;
}

.generating-header .loading-icon {
  animation: rotating 2s linear infinite;
  font-size: 16px;
}

.generating-placeholder {
  padding: 24px;
  text-align: center;
  color: #667eea;
}

.generating-tip {
  margin-top: 16px;
  font-size: 14px;
  color: #909399;
  font-weight: 400;
}

.input-section,
.result-section,
.generating-section,
.error-section {
  width: 100%;
  animation: fadeInUp 0.4s ease-out;
}

/* 输入框样式 */
.prompt-input,
.sql-input {
  margin-top: 20px;
}

.prompt-input :deep(.el-textarea__inner),
.sql-input :deep(.el-textarea__inner) {
  border-radius: 12px;
  border: 2px solid rgba(102, 126, 234, 0.1);
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  line-height: 1.6;
  transition: all 0.3s ease;
  background: rgba(248, 249, 255, 0.5);
  padding: 16px;
}

.prompt-input :deep(.el-textarea__inner):focus,
.sql-input :deep(.el-textarea__inner):focus {
  border-color: #667eea;
  box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
  background: white;
}

.input-actions {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

.input-actions .el-button {
  padding: 14px 36px;
  border-radius: 25px;
  font-weight: 600;
  font-size: 15px;
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.input-actions .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 24px rgba(102, 126, 234, 0.4);
}

.sql-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.sql-result {
  margin-top: 16px;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background-color: #f8fafc;
}

.sql-result h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.parsed-fields-preview {
  margin-top: 16px;
}

.parsed-fields-preview :deep(.el-table) {
  font-size: 13px;
  border-radius: 8px;
  overflow: hidden;
}

.parsed-fields-preview :deep(.el-table th) {
  background: linear-gradient(135deg, #f8f9ff 0%, #ffffff 100%);
  font-weight: 600;
  color: #667eea;
  border-color: rgba(102, 126, 234, 0.1);
}

.parsed-fields-preview :deep(.el-table td) {
  padding: 12px 8px;
  border-color: rgba(102, 126, 234, 0.1);
}

.parsed-fields-preview :deep(.el-table--border) {
  border-color: rgba(102, 126, 234, 0.1);
}

.sql-error {
  margin-top: 16px;
}

.sql-error :deep(.el-alert) {
  border-radius: 6px;
}

/* SQL 输入框样式优化 */
:deep(.el-textarea__inner) {
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.4;
}

/* 标签页样式优化 */
:deep(.el-tabs__item) {
  font-weight: 500;
}

:deep(.el-tabs__item.is-active) {
  color: #409eff;
  font-weight: 600;
}

/* 提示词模板样式 */
.prompt-templates {
  margin-top: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #f8f9ff 0%, #ffffff 100%);
  border-radius: 12px;
  border: 1px solid rgba(102, 126, 234, 0.1);
}

.templates-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.templates-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.templates-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 12px;
}

.template-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: white;
  border: 1px solid rgba(102, 126, 234, 0.1);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.05);
}

.template-card:hover {
  border-color: #667eea;
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.15);
  transform: translateY(-2px);
}

.template-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
  font-size: 18px;
  flex-shrink: 0;
}

.template-content {
  flex: 1;
  min-width: 0;
}

.template-title {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
  margin-bottom: 4px;
}

.template-desc {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}
</style>
